// 主图添加{ bobotitle }

import { upDataImage } from "@Api/shopsApi"
import {
  Button,
  Icon,
  InputNumber,
  message,
  Popover,
  Slider,
  Space,
  Upload,
  Radio,
  Modal,
  Spin,
  imgPreview,
  ImgCrop,
  Empty,
  ImgDefault,
  Checkbox,
  Input
} from "@bytedance/mona-ui"
import React, { useState, useEffect, useImperativeHandle, forwardRef, useMemo } from "react"
import { store, useAppDispatch, useAppSelector } from "~store"
import { fengeDeteailImage } from './copyDataFomate'

// import { setAiCretedList } from "~store/controller/jinritemaiCopyGoods"

import {
  setDetailsAddImageList
} from "~store/controller/jinritemaiCopyGoods"

import "./index.scss"

import { DndContext, useSensors, useSensor, MouseSensor } from "@dnd-kit/core";
import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import DeteilCanvas from '../../componets/DeteilCanvas'
import { upImageItemFunc, getObjectURL, urlToBase64, shuffleArray } from './copyDataFomate'
import AiOpenImageComp from './AIImageComp'

let openIndex
let addTextTime
function getMoveItemInfo(getitrem: number, bi) {
  let mobeInfo = {}
  switch (getitrem) {
    case 1:
      mobeInfo = {
        left: 5,
        top: 5,
        offseX: 5,
        offsetY: 5,
        width: 15,
        height: Math.round(bi * 15)
      }
      break
    case 2:
      mobeInfo = {
        left: 0,
        top: 0,
        offseX: 0,
        offsetY: 0,
        width: 100,
        height: 100
      }
      break
    default:
      break
  }
  return mobeInfo
}
// 图片组件
const MoveImageBpx = (props: any) => {
  const {
    imageData,
    removState,
    allList,
    onChange,
    index
  } = props
  if (!imageData) return null

  const { setNodeRef, listeners, transform, transition } = useSortable({ id: imageData.id })

  const styles: any = {
    transform: CSS.Transform.toString(transform),
    transition: transition,
    zIndex: removState && removState === imageData.id ? 10 : 1,
    position: removState && removState === imageData.id ? 'relative' : 'static',
    opacity: removState && removState === imageData.id ? 0.5 : 1,
  }

  return (
    <div className="moverbox" style={styles} ref={setNodeRef} {...listeners}>
      <Spin spinning={imageData.islodin}>
        <div className="seterimage" style={{
          cursor: 'move'
        }}>
          <img src={imageData.url} className="couyimage" />
          <div className="conterItemStatus">
            <div className="itemcie">
              <Icon type="SeeIcon" className="setIcon" onClick={() => {
                imgPreview({
                  defaultIndex: index,
                  imgUrl: allList.map((res => res.url)),
                })
              }}></Icon>
            </div>
            <div className="itemcie">
              <Icon type="ClipIcon" className="setIcon" onClick={() => {
                ImgCrop.imgCropModalFun({
                  image: imageData?.url,
                  modalProps: {
                    onOk: (e, newfile) => {
                      console.log(e, newfile)
                      const imageUrl = getObjectURL(newfile)
                      allList[index].url = imageUrl
                      allList[index].islodin = true
                      allList[index].isNewImage = true
                      allList[index].upStatus = false
                      onChange && onChange([...allList])
                      urlToBase64(imageUrl).then(resUrl => {
                        upImageItemFunc(resUrl).then((upImages) => {
                          allList[index].url = upImages.data[0]
                          allList[index].islodin = false
                          allList[index].isNewImage = true
                          allList[index].upStatus = true
                          onChange && onChange([...allList])
                        })
                      })
                    },
                  },
                });
              }}></Icon>
            </div>
            <div className="itemcie">
              <Icon type="DeleteIcon" className="setIcon" onClick={() => {
                allList.splice(index, 1)
                allList.forEach((res, index) => {
                  res.id = index + 1
                })
                onChange && onChange([...allList])
              }}></Icon>
            </div>
          </div>
        </div>
      </Spin>

    </div>
  )
}

const { AddIcon } = Icon
// 主
const AddBodersContent = (props: any, ref) => {
  if (!props) return null
  const {
    goodsDetellData,
    goodPrettify,
    copyGoodConfig,
    searchWord
  } = props

  if (!goodPrettify) return
  const dispatch = useAppDispatch()

  // 转化图片列表数据
  function getPricImageInfo(moveinfo: any) {
    const picImages =
      goodPrettify?.map((res: any, index: number) => {
        return {
          id: index + 1,
          url: res,
          islodin: false,
          isNewImage: false,
          upStatus: true,
          watermark: {
            ...moveinfo,
            bi: 0,
            pageX: 0,
            pageY: 0,
            url: null,
            moveStatus: false,
            clickTime: 0,
            setImageStatus: false,
            mergeurl: null
          },
          moveImageStatus: false,
          translateX: index * 120,
          left: 0,
          top: 0,
          pageX: 0,
          pageY: 0,
          zIndex: 1,
          elemCenterPx: 0,
          index
        }
      }) || []
    return picImages
  }

  const { copynum } = copyGoodConfig

  const [picImageList, setPicImageList] = useState<any[]>([])
  useEffect(() => {
    if (picImageList.length === copynum) return
    const addConter = copynum - picImageList.length
    if (addConter > 0) {
      for (let i = 0; i < addConter; i++) {
        picImageList.push({
          config: {
            selectType: 1,
            setConteNum: 5,
            lodingFenge: false
          },
          list: getPricImageInfo(getMoveItemInfo(1, 0))
        })
      }
    } else {
      picImageList.splice(addConter, Math.abs(addConter))
    }
    setPicImageList([...picImageList])
  }, [copynum])
  // useEffect(() => {
  //   dispatch(setDetailsAddImageList(JSON.parse(JSON.stringify(picImageList))))
  // }, [picImageList])
  useImperativeHandle(ref, () => ({
    picImageList
  }));

  const [canvasStatus, setCanvasStatus] = useState(false)
  const [addTextUrls, setAddTextUrls] = useState('')
  const [addAllTextImageConfigs, setAddAllTextImageConfigs] = useState<any>({})
  const [showAiDeteailListModeal, setShowAiDeteailListModeal] = useState(false)
  // const [seletImageIndex, setSeletImageIndex] = useState(-1)
  const aiCretedList = useAppSelector((state) => state.jinritemaiCopyGoods.aiCretedList)
  // 拖拽结束后的操作
  const [fengeNum, setFengeNum] = useState(1)
  function refoterDetetilImageFunc(list, num, index) {
    // console.log('list, num', list, num)
    return <Space>
      <span>分割数量:</span> <InputNumber min={1} max={50} size="small" value={num} onChange={(e: number) => {
        // setFengeNum(e)
        picImageList[index].config.setConteNum = e
        setPicImageList([...picImageList])
      }} placeholder="输入分割数量">
      </InputNumber>
      <Button onClick={async () => {
        picImageList[index].config.lodingFenge = true
        setPicImageList([...picImageList])
        const getDtas = await fengeDeteailImage(list, num)
        picImageList[index].config.lodingFenge = false
        picImageList[index].list = getDtas.map((res, indexche) => {
          upImageItemFunc(res).then((upImages) => {
            // console.log('indexche', indexche)
            const itemtser = picImageList[index].list.find((item) => item.id == indexche + 1)
            itemtser.url = upImages.data[0]
            itemtser.islodin = false
            itemtser.upStatus = true
            setPicImageList([...picImageList])
          })
          return {
            id: indexche + 1,
            url: res,
            islodin: true,
            isNewImage: true,
            upStatus: false
          }
        })
        setPicImageList([...picImageList])
        // console.log('getDtas', getDtas)
      }}
        type="primary"
        size="small"
      >确认分割</Button>
    </Space>
  }

  return (
    < div style={{
      marginLeft: 0,
      cursor: 'auto'
    }}>
      <Space direction="vertical">
        <div className="itemboxcone">
          <Space direction="vertical">
            <div className="sye" style={{
              color: '#000',
              fontSize: 14,
              fontWeight: 900,
            }}>
              批量调整
            </div>
            <Space>

              <Button size="mini" onClick={() => {
                openIndex = 'ALL'
                setCanvasStatus(true)
              }}>批量添加详情文字</Button>
              <Button size="mini" onClick={() => {
                // setSeletImageIndex()
                // openIndex = indexbser
                // setShowAiDeteailListModeal(true)

                picImageList.forEach(refoItem => {
                  refoItem.list = shuffleArray(refoItem.list)
                })

                setPicImageList([...picImageList])

              }}>打乱全部详情图</Button>
              {/* <Button onClick={() => {
                // setSeletImageIndex()
                openIndex = 'ALL'
                setShowAiDeteailListModeal(true)
              }}>批量添加详情AI生成图片</Button> */}
            </Space>
          </Space>
        </div>
        {...picImageList.map((picImages, indexbser) => {
          return (<Spin spinning={picImages.config.lodingFenge}>
            <div className="imsgecontenbo" key={indexbser}>
              <Space direction="vertical">
                <span>
                  详情图{indexbser + 1} ({picImages.list.length}/50)
                </span>
                <Space size={20} align="start">
                  <DetelesImage data={picImages.list}></DetelesImage>
                  <Space direction="vertical" size={75}>
                    <div className="imageMoveBox topconter">
                      <RomoItemBox
                        data={picImages.list}
                        onChange={(data) => {
                          picImages.list = data
                          setPicImageList([...picImageList])
                        }}
                      />
                    </div>
                    <div className="imageMoveBox">
                      <Space>
                        <Button onClick={() => {
                          // 创建input 获取上传图片文件
                          const inputfile = document.createElement('input')
                          // 设置支持多选
                          inputfile.multiple = true;
                          inputfile.accept = 'image/*';
                          inputfile.type = "file"
                          inputfile.click()
                          inputfile.onchange = async (event) => {
                            const files = event.target.files;
                            const imageList = []
                            for (let i = 0; i < files.length; i++) {
                              const imageUrl: any = getObjectURL(files[i])
                              imageList.push(imageUrl)
                              // 获取图片文件的大小
                              console.log('图片大小', files[i].size / 1024 / 1024)
                              if (files[i].size / 1024 / 1024 > 5) {
                                return message.warning('图片大小不能超过5M')
                              }

                              urlToBase64(imageUrl).then(resUrl => {
                                upImageItemFunc(resUrl).then((upImages) => {
                                  console.log('upImages', upImages)
                                  const itemtser = picImages.list.find((item) => item.id == `plyer${i}`)
                                  console.log('itemtser', itemtser)
                                  if (itemtser) {
                                    itemtser.url = upImages.data[0]
                                    itemtser.islodin = false
                                    itemtser.upStatus = true
                                    setPicImageList([...picImageList])
                                  }
                                })
                              })
                              picImages.list.push({
                                id: `plyer${i}`,
                                url: imageUrl,
                                islodin: true,
                                isNewImage: true,
                                upStatus: false
                              })
                            }
                            if (picImages.list.length > 50) {
                              message.warning('详情图最多支持50张')
                              picImages.list = picImages.list.splice(0, 50)
                            }
                            setPicImageList([...picImageList])
                            // console.log('imageList', imageList)

                            // const getIyer = imageList.splice(0, 5)

                            // getIyer.forEach((item, index) => {
                            //   if (!picImages.list[index]) {
                            //     picImages.list[index] = JSON.parse(JSON.stringify(picImages.list[0]))
                            //   }
                            //   picImages.list[index].url = item
                            // })
                            // for (let i = 0; i < picImages.list.length; i++) {
                            //   picImages.list[i].id = i + 1
                            // }
                            // setPicImageList([...picImageList])
                          }

                        }}>上传详情图</Button>
                        <Button onClick={() => {
                          openIndex = indexbser
                          setCanvasStatus(true)
                        }}>添加文字</Button>
                        <Button onClick={() => {
                          // setSeletImageIndex()
                          openIndex = indexbser
                          setShowAiDeteailListModeal(true)
                        }}>添加AI生成图片</Button>
                        <Button onClick={() => {
                          // setSeletImageIndex()
                          // openIndex = indexbser
                          // setShowAiDeteailListModeal(true)
                          console.time('开始1')
                          console.log(' picImages.list ', picImages.list)
                          picImages.list = shuffleArray(picImages.list)
                          console.log('打乱结果', picImageList)
                          setPicImageList([...picImageList])
                          console.timeEnd('开始1')
                        }}>打乱详情图</Button>
                        <Popover content={refoterDetetilImageFunc(picImages.list, picImages.config.setConteNum, indexbser)}>
                          <Button type="secondary">重新切割</Button>

                        </Popover>
                      </Space>

                    </div>
                  </Space>


                  {false && <div>
                    <Space>
                      <Upload
                        btnText={`上传${picImages.config.selectType === 1 ? '图标' : '边框'}`}
                        btnType="default"
                        btnIcon={<AddIcon />}
                        maxCount={1}
                        showUploadList={false}
                        beforeUpload={(file) => {
                          const fileType = /\image\/\/*/
                          if (fileType.test(file.type)) {
                            const imageUrl = getObjectURL(file)
                            var img: any = new Image()
                            img.src = imageUrl
                            img.addEventListener("load", () => {
                              const iw = img.width
                              const ih = img.height
                              const bi = ih / iw
                              picImages.list.forEach((picItem) => {
                                picItem.watermark.url = imageUrl
                                picItem.watermark.bi = bi
                                picItem.watermark.height = picImages.config.selectType === 1 ? Math.round(
                                  bi * picItem.watermark.width
                                ) : 100
                              })
                              setPicImageList([...picImageList])
                            })

                            return
                          }
                          message.error("仅支持图片")
                        }}
                      />
                      {/* <Button type="link">历史{picImages.config.selectType === 1 ? '图标' : '边框'}</Button> */}
                      <Button
                        type="link"
                        onClick={() => {
                          picImages.list.forEach((item) => {
                            const infodater = getMoveItemInfo(
                              picImageList[indexbser].config.selectType,
                              item.watermark.bi
                            )
                            const mergewet = Object.assign(item.watermark, infodater)
                            item.watermark = mergewet
                          })
                          setPicImageList([...picImageList])
                        }}>
                        恢复默认
                      </Button>
                      <Button
                        type="link"
                        onClick={() => {
                          picImages.list.forEach((picItem) => {
                            picItem.watermark.url = null
                            picItem.watermark.bi = 0
                            picItem.watermark.height = 0
                          })
                          setPicImageList([...picImageList])
                        }}>
                        清除所有{picImages.config.selectType === 1 ? '图标' : '边框'}
                      </Button>
                    </Space>
                  </div>}
                  {/* </div> */}
                </Space>
              </Space>
            </div>
          </Spin>)

        })
        }
      </Space >
      <Modal
        visible={canvasStatus}
        onOk={() => {
          // console.log('addAllTextImageConfigs1111', addAllTextImageConfigs)
          // console.log('openIndex2222', openIndex)
          if (openIndex === 'ALL') {
            addAllTextImageConfigs.forEach((itemImage, indexImage) => {
              if (itemImage.betUrl) {
                let upTiemImaghId = picImageList[indexImage].list.length + 1

                upImageItemFunc(itemImage.betUrl).then((upImages) => {
                  const itemtser = picImageList[indexImage].list.find((item) => item.id == upTiemImaghId)
                  itemtser.url = upImages.data[0]
                  itemtser.islodin = false
                  itemtser.upStatus = true
                  setPicImageList([...picImageList])
                })

                picImageList[indexImage].list.push({
                  id: upTiemImaghId,
                  url: itemImage.betUrl,
                  islodin: true,
                  isNewImage: true,
                  upStatus: false
                })
                setPicImageList([...picImageList])
              }
            })
            setCanvasStatus(false)
            return
          }
          if (addTextUrls) {
            let upTiemImaghId = picImageList[openIndex].list.length + 1
            upImageItemFunc(addTextUrls).then((upImages) => {
              const itemtser = picImageList[openIndex].list.find((item) => item.id == upTiemImaghId)
              itemtser.url = upImages.data[0]
              itemtser.islodin = false
              itemtser.upStatus = true
              setPicImageList([...picImageList])
            })
            picImageList[openIndex].list.push({
              id: upTiemImaghId,
              url: addTextUrls,
              islodin: true,
              isNewImage: true,
              upStatus: false
            })
            setPicImageList([...picImageList])
          }
          setCanvasStatus(false)
        }}
        onCancel={() => setCanvasStatus(false)}
        title='添加详情文字'
        width={1000}
        bodyStyle={{
          padding: 0,
        }}
        wrapClassName="addBodersModal"
        destroyOnClose={true}
      >
        <DeteilCanvas searchWord={searchWord} copynum={copynum} openIndex={openIndex} onChangeUrl={(e) => {
          console.log('interUrls', e)
          setAddTextUrls(e)
        }}
          onChangeUrlAll={(e) => {
            setAddAllTextImageConfigs(e)
          }}
        />
      </Modal>
      <Modal
        visible={showAiDeteailListModeal}
        onCancel={() => setShowAiDeteailListModeal(false)}
        onOk={() => {
          // console.log('picImageList', picImageList[openIndex])
          if (addTextTime) return
          addTextTime = setTimeout(() => {
            clearTimeout(addTextTime)
            addTextTime = null
          }, 2000)
          if (picImageList[openIndex]?.config?.selectIndex?.length) {
            picImageList[openIndex]?.config?.selectIndex?.forEach((items, index) => {
              console.log('aiCretedList', aiCretedList[items])
              let upTiemImaghId = picImageList[openIndex].list.length + 1
              picImageList[openIndex].list.unshift({
                id: upTiemImaghId,
                url: aiCretedList.filter(res => {
                  return res.extra_properties && res.extra_properties.schema_doc
                })[items].img_url,
                // islodin: true,
                // isNewImage: true,
                // upStatus: false
                islodin: false,
                isNewImage: true,
                upStatus: true
              })
              // picImages.list.push({
              //   id: upTiemImaghId,
              //   url: imageUrl,
              //   islodin: true,
              //   isNewImage: true,
              //   upStatus: false
              // })
            })
            setPicImageList([...picImageList])
          }
          setShowAiDeteailListModeal(false)
        }}
        width={1000}
        title="添加AI详情图"
        wrapClassName="addBodersModal"
        destroyOnClose={true}
      >
        {!aiCretedList?.length ? <NoAilListBox goodsDetellData={goodsDetellData} /> : <AiImageListContent
          seletImageIndex={picImageList[openIndex]?.config?.selectIndex || []}
          imageList={aiCretedList}
          onChangeItems={(data) => {
            console.log('data', data)
            console.log('picImageList', picImageList[openIndex])
            picImageList[openIndex].config.selectIndex = data
            // setPicImageList([...picImageList])
            // setSeletImageIndex(data)
          }} />}
        {/* ailenthen{aiCretedList.length} */}
      </Modal>
    </div >
  )
}
const NoAilListBox = (props?) => {
  const { goodsDetellData } = props
  // console.log('goodsDetellData', goodsDetellData)
  // if(!goodsDetellData) return
  const [addIfameStatus, setAddIfameStatus] = useState(false)
  // const [setAddInfoData, setAddInfoDataFun] = useState([])
  return <div>
    <Empty className="empty-img-emotion" >
      <Button type="primary" onClick={() => setAddIfameStatus(true)}>AI生成</Button>
    </Empty>
    <AiOpenImageComp
      visible={addIfameStatus}
      onCancel={() => setAddIfameStatus(false)}
      type='4'
      setAddInfoData={[[{
        index: 0,
        priindex: 0,
        url: goodsDetellData?.pic[0]
      }]]}
      product_id={goodsDetellData?.product_id}
      img_format={1}
      onChangeImage={(data) => {
        // console.log('data', data)
        data.forEach((item, index) => {
          item.forEach((iyee, its) => {
            if (iyee.res_url) {
              // picImageList[iyee.priindex].list[iyee.index].url = iyee.res_url
            }
          })
        })
        // setSetAddInfoData([...picImageList])
        setAddIfameStatus(false)
      }}
    ></AiOpenImageComp>
  </div>
}

const AiImageListContent = (props?) => {
  const { imageList, onChangeItems, seletImageIndex } = props
  if (!imageList) return <NoAilListBox />
  let imageData = imageList.filter(res => {
    return res.extra_properties && res.extra_properties.schema_doc
  })
  const [selectImageContent, setSelectImageContent] = useState<any[]>(seletImageIndex)
  const setecImageImage = (index) => {
    // console.log('点击选择', index)
    if (selectImageContent.includes(index)) {
      selectImageContent.splice(selectImageContent.indexOf(index), 1)
    } else {
      selectImageContent.push(index)
    }
    setSelectImageContent([...selectImageContent])
  }
  useEffect(() => {
    onChangeItems && onChangeItems(selectImageContent)
  }, [selectImageContent])
  return <Space
    wrap
    className="moverbox"
    size={12}
    style={{
      width: '100%'
    }}>
    {imageData.map((img, index: any) => {
      return (<div key={index} className="seterimage" style={{ width: 130, height: 130 }}>
        <ImgDefault
          style={{ width: 130, height: 130 }}
          imgSrc={(() => {
            const imgae = img.img_url.replace('obj/', '')
            return imgae + '~130x130_q75.image'
          })()
          }
          mask={false}
          className="seltinger"
          onClick={() => { setecImageImage(index) }}
        ></ImgDefault>
        <Checkbox className="selectStatus" size="large" checked={selectImageContent.includes(index)} onClick={() => { setecImageImage(index) }}></Checkbox>
        <div className="conterItemStatus">
          <div className="itemcie">
            <Icon type="SeeIcon" className="setIcon" onClick={() => {
              imgPreview({
                defaultIndex: index,
                imgUrl: imageData.map((res => res.img_url)),
              })
            }}></Icon>
          </div>
        </div>
      </div>)
    })}
  </Space >
}

const DetelesImage = (props) => {
  const { data } = props
  if (!data) return null
  return (<>
    <div className="detileRefos" style={{
      background: '#fff',
      border: '1px solid #dcdde0',
      borderRadius: 4,
      boxSizing: 'border-box',
      flex: '0 0 auto',
      height: 545,
      width: 300

    }}>
      <div className="title" style={{
        color: '#85878a',
        fontSize: 12,
        height: 32,
        lineHeight: '32px',
        padding: '0 12px',
        background: '#f9f9fa'
      }}>详情预览</div>
      <div className="imageList" style={{
        width: '100%',
        height: 'calc(100% - 32px)',
        overflow: 'auto'
      }}>
        {data.map(item => {
          return <img src={item.url} alt="" style={{
            width: '100%'
          }} key={item.id} />
        })}
      </div>
    </div >
  </>)
}

const RomoItemBox = (props: any) => {
  const { data, onChange } = props

  const [list, setList] = useState<any[]>([])

  useEffect(() => {
    if (data !== list) {
      onChange && onChange(list)
    }
  }, [list])
  const [removState, setRemoveState] = useState(false)
  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 5, // 按住不动移动5px 时 才进行拖拽, 这样就可以触发点击事件
      },
    })
  )
  // console.log('渲染')
  useMemo(() => {
    setList(data)
  }, [data, onChange])
  if (!list) return null
  return <DndContext
    sensors={sensors}
    onDragStart={(e: any) => {
      const { active } = e
      setRemoveState(active.id)
    }}
    onDragEnd={(e) => {
      setRemoveState(false)
      const { active, over } = e
      if (!over || !over.id) return
      let activeIndex
      let overIndex
      list.forEach((val, index) => {
        if (val.id === active.id) {
          activeIndex = index
        }
        if (val.id === over.id) {
          overIndex = index
        }
      })
      setList(items => {
        const adddata = arrayMove(items, activeIndex, overIndex)
        return adddata
      })
    }}>
    <SortableContext items={[...list]}>
      <div className="topmovuerfoter-tower">
        {list.map((res: any, index: number) => {
          return (
            <MoveImageBpx
              key={res.id}
              imageData={res}
              removState={removState}
              allList={list}
              onChange={setList}
              index={index}
            />)
        })}
      </div>

    </SortableContext>
  </DndContext>
}



export default forwardRef(AddBodersContent)

